package com.wanghlme.day21.servlet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Arrays;
import java.util.Map;

public class Buy extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        shop(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }

    public void shop(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=UTF-8");
        Map<String, String[]> map = request.getParameterMap();
        for (String key : map.keySet()) {
            System.out.println("key= " + key + " and value= " + Arrays.toString(map.get(key)));
        }
        String str = map.get("customer-number")[0];
        int fruit1 = Integer.parseInt(map.get("fruit-1") == null ? "0" : map.get("fruit-1")[0]);
        int fruit2 = Integer.parseInt(map.get("fruit-2") == null ? "0" : map.get("fruit-2")[0]);
        int fruit3 = Integer.parseInt(map.get("fruit-3") == null ? "0" : map.get("fruit-3")[0]);
        int weight1 = Integer.parseInt(map.get("weight-1") == null ? "0" : map.get("weight-1")[0]);
        int weight2 = Integer.parseInt(map.get("weight-2") == null ? "0" : map.get("weight-2")[0]);
        int weight3 = Integer.parseInt(map.get("weight-3") == null ? "0" : map.get("weight-3")[0]);
        String pay = map.get("pay")[0];
        float price = 0.0f;
        if (fruit1 == 1) {
            price += (weight1 * 2.5f);
        }
        if (fruit2 == 2) {
            price += (weight2 * 7.5f);
        }
        if (fruit3 == 3) {
            price += (weight3 * 5.0f);
        }
        PrintWriter out = null;
        try {
            out = response.getWriter();
        } catch (IOException e) {
            e.printStackTrace();
        }
        assert out != null;
        String page = "<div><p><br/></p><p>购物信息：</p><p>编号：" + str + "</p><p>商品总额：" + price + "</p><p>付款方式：" + pay + "</p></div>";
        out.write(page);
        out.flush();
        out.close();
    }
}
